package com.wu.store.common.util;

import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: lifuzhao
 * @Date: 2020-02-13 10:12
 * @Project store
 */
public class FileUtils {
	private static String dir = System.getProperty("user.dir") + "/goodsImg/";
	private static String OS = System.getProperty("os.name").toLowerCase();

	public static String generateFile(String base64, String prefix) throws Exception {
		File file = new File(dir);
		if (!file.exists()) {
			boolean mkdir = file.mkdir();
			if (!mkdir) {
				throw new Exception("创建文件夹失败，请手动创建" + dir);
			}
		}
		FileOutputStream write = null;

		if (StringUtils.isEmpty(base64)) {
			throw new Exception("请上传图片");
		}
		Pattern compile = Pattern.compile("^data.+base64,");
		Matcher matcher = compile.matcher(base64);
		if (!matcher.find()) {
			return base64;
		}
		String fileName = prefix + "_" + UUID.randomUUID().toString().substring(0, 4);
		String suffix = ".png";
		if (base64.startsWith("data:image/jpeg;")) {
			suffix = ".jpg";
		} else if (base64.startsWith("data:image/png;")) {
			suffix = ".png";
		}
		base64 = matcher.replaceFirst("");
		String filePath = FileUtils.dir + fileName + suffix;
		Base64.Decoder decoder = Base64.getDecoder();
		try {
			write = new FileOutputStream(filePath);
			byte[] b = decoder.decode(base64);
			write.write(b);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (write != null) write.flush();
				if (write != null) write.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "/goodsImg/" + fileName + suffix;
	}

	public static void main(String[] args) {
		System.out.println(OS);
	}
}
